import {
    hierarchyToTree, setTreeSpan,
    setTreeAttr, setTreeLeafCount,
    getTreeLeaf, getArrayOfTreeNode, getInitMatrix,
    getAixsXMatrixNew, expandInit, getAllChildren,
    treeFilter,getAllParent
} from './treeUtil.js'
import {getValueForFilter} from "./xUtil.js";

/*

* */

const splitChar = ',';

export default class xTableData {
    // vCfg.data 是原始数据无任何操作的
    vCfg;
    //过滤后的数据
    vAfterFilterData;
    //这里是过滤后，排好序的数据
    vAfterSortData;
    // 这里是 过滤后，排序后，分页后的数据
    vData;
    vHeadMatrix;
    //column 的key
    vKeys;
    vSortKey;
    vDataMatrix;
    vIsTreeTable;
    vFilterKeys = {}

    /*定义变量 结束*/

    initTree() {
        this.vCfg.data = hierarchyToTree(this.vCfg.data);
        setTreeAttr(this.vCfg.data);

        // clear filter
        treeFilter(this.vCfg.data, (node) => true, null);
        // filter
        if (JSON.stringify(this.vFilterKeys) != '{}') {
            treeFilter(this.vCfg.data, this.cbTreeFilter.bind(this));
        }

        this.vData = getArrayOfTreeNode(this.vCfg.data);
        //树展开初始化
        if (this.vCfg.cols[0].expand)
            expandInit(this.vData, this.vCfg.cols[0].expand)
    }

    initColumn() {
        setTreeAttr(this.vCfg.cols);
        setTreeLeafCount(this.vCfg.cols);
        setTreeSpan(this.vCfg.cols);
        this.vHeadMatrix = getAixsXMatrixNew(this.vCfg.cols);
        this.vKeys = getTreeLeaf(this.vCfg.cols);
    }

    prepare(cfg) {
        this.vCfg = cfg;
        this.vIsTreeTable = this.vCfg.cols[0].type == 'tree' ? true : false;
        this.initColumn();
        if (this.vIsTreeTable)
            this.initTree();
        else {
            this.filter();
            this.sort();
            this.pageData();
        }
        this.vDataMatrix = getInitMatrix(this.vData.length, this.vKeys.length);
        this.fillMatrix();
        if (!this.vIsTreeTable && this.vCfg.merge)
            this.mergeMatrix();
    }

    isActiveFilter(field) {
        return this.vFilterKeys[field] ? true : false;
    }

    getSelectByField(field) {
        let select = [];
        if (this.vFilterKeys[field])
            this.vFilterKeys[field].forEach(k => select.push(field + ',' + k));
        return select;
    }

    fillMatrix() {
        for (let i = 0; i < this.vData.length; i++) {
            for (let j = 0; j < this.vKeys.length; j++) {
                this.vDataMatrix[i][j] = {key: this.vKeys[j], item: this.vData[i]}
            }
        }
    }

    mergeMatrix() {
        for (let k of this.vCfg.merge) {
            let index = this.getKeyIndex(k);
            if (index > -1) {
                let tmpItem = this.vDataMatrix[0][index];
                tmpItem.rowspan = 1;
                for (let i = 1; i < this.vDataMatrix.length; i++) {
                    if (tmpItem.item[k] == this.vDataMatrix[i][index].item[k]) {
                        tmpItem.rowspan += 1;
                        this.vDataMatrix[i][index] = null;
                    }
                    else {
                        tmpItem = this.vDataMatrix[i][index];
                        tmpItem.rowspan = 1;
                    }
                }
            }
        }
    }

    getKeyIndex(key) {
        let index = -1;
        for (let j = 0; j < this.vKeys.length; j++) {
            if (this.vKeys[j].$data == key) {
                index = j;
                break;
            }
        }
        return index;
    }

    //只能对过滤后的数据 排序
    sort() {
        if (this.vSortKey) {
            let key = this.getKeyByField(this.vSortKey.key);
            let tmpData = this.vAfterFilterData || this.vCfg.data;
            this.vAfterSortData = [...tmpData];
            if (this.vSortKey.type != 'no') {
                let factor = this.vSortKey.type == 'desc' ? -1 : 1;
                this.vAfterSortData.sort((a, b) => {
                    let result;
                    if (key.DataType && key.DataType.toLowerCase() == 'number')
                        result = a[key.$data] - b[key.$data];
                    else
                        result = a[key.$data] + '' > b[key.$data] + '' ? 1 : a[key.$data] == b[key.$data] ? 0 : -1;
                    return result * factor;
                })
            }
        }
    }


    /*
    注意这里的数据 不能取所有的数据
     要取 非自己字段 过滤后 的数据
    * */

    getKeySet(field) {
        let key = this.getKeyByField(field);

        let items = this.vCfg.data;
        let keySet = new Set();
        if (this.vIsTreeTable) {
            items = getAllChildren({children: this.vCfg.data});
        }

        for (let d of items) {
            let ok = true;
            for (let fk in this.vFilterKeys) {
                if (fk != field) {
                    ok = (this.getKeyByField(fk).type == 'tag') ?
                        this.tagsMatch(this.vFilterKeys[fk], d[fk]) :
                        this.vFilterKeys[fk].includes(d[fk] + '');
                    if (!ok)
                        break;
                }
            }
            if (ok) {
                if (key.type == 'tag') {
                    let tags = d[key.$data].split(',');
                    tags.forEach(t => keySet.add(t.split(' ')[0]));
                } else
                    keySet.add(d[field]);
            }

        }

        let keyArray = [...keySet];
        if (key.type != 'tree') {
            keyArray.sort((a, b) => {
                let result;
                if (key.DataType && key.DataType.toLowerCase() == 'number') {
                    result = a - b;
                    if (getValueForFilter(a) == '(空白)')
                        result = 1;
                    if (getValueForFilter(b) == '(空白)')
                        result = -1;
                }
                else {
                    result = a > b ? 1 : a == b ? 0 : -1;
                    if (getValueForFilter(a) == '(空白)')
                        result = 1;
                    if (getValueForFilter(b) == '(空白)')
                        result = -1;
                }
                return result;
            });
        }

        let keys = [];
        keyArray.forEach(k => keys.push({code: field + ',' + k, name: k}));
        return keys;
    }

    getKeyByField(field) {
        let key;
        for (let k of this.vKeys) {
            if (k.$data == field) {
                key = k;
                break;
            }
        }
        return key;
    }

    // 这里key参数 是 字段名
    clearFilterByField(field) {
        this.vFilterSet.forEach(f => {
            if (f.split(splitChar)[0] == field) {
                this.vFilterSet.delete(f);
            }
        })
    }

    addSelect(field, select) {
        this.vFilterKeys[field] = [];
        for (let s of select) {
            this.vFilterKeys[field].push(s.split(',')[1]);
        }
    }

    cbTreeFilter(node) {
        //默认是保留
        let result = true;
        for (let field in this.vFilterKeys) {
            let inSelect = false;
            if(field=='name'){
                let parents = getAllParent(node);
                parents.push(node);

                for(let item of parents){
                    if(this.vFilterKeys[field].includes(item[field] + '')){
                        inSelect = true;
                        break;
                    }
                }

                if (!inSelect) {
                    result = false;
                    break;
                }
            }
            /*
            let inSelect = (this.getKeyByField(field).type == 'tag') ?
                this.tagsMatch(this.vFilterKeys[field], node[field]) :
                this.vFilterKeys[field].includes(node[field] + '');
             */
            // tree 只能是tree 的过滤模式

        }
        return result;
    }

    filter() {
        this.vAfterFilterData = [];
        for (let d of this.vCfg.data) {
            let ok = true;
            for (let field in this.vFilterKeys) {
                let inSelect = (this.getKeyByField(field).type == 'tag') ?
                    this.tagsMatch(this.vFilterKeys[field], d[field]) :
                    this.vFilterKeys[field].includes(d[field] + '');
                if (!inSelect) {
                    ok = false;
                    break;
                }
            }
            if (ok)
                this.vAfterFilterData.push(d);
        }

    }

    /*
    *  注意 tags  数据格式 "紫色 purple,绿色 green" 要拆分 才能匹配
    *  拆分后匹配上一个 就返回 true
    * */
    tagsMatch(selects, tags) {
        let isMatch = false;
        for (let tag of tags.split(',')) {
            if (selects.includes(tag.split(' ')[0])) {
                isMatch = true;
                break;
            }
        }
        return isMatch;
    }

    pageData() {
        if (this.vCfg.pagination && !this.vCfg.ajax) {
            let page = this.vCfg.pagination;
            let pageIndex = page.pageIndex || 1;
            let pageSize = page.pageSize || 10;
            let _start = (pageIndex - 1) * pageSize;
            let _end = pageIndex * pageSize;
            //获取数据
            let tmpData = this.vAfterSortData || this.vAfterFilterData || this.vCfg.data;
            this.vData = tmpData.slice(_start, _end);
        } else
            this.vData = this.vAfterSortData || this.vAfterFilterData || this.vCfg.data;
    }
}